<?php

header("content-type: text/html; charset=iso-8859-1;", true);

$dbHost = "127.0.0.1:3306";
$dbUser = "root";
$dbPass = "babilonia";
$dbData = "protocolo";

$conn = mysql_connect($dbHost,$dbUser,$dbPass) or die(mysql_error());
mysql_select_db($dbData,$conn) or die(mysql_error());

mysql_query("SET NAMES 'utf8';");

if (!isset($_SESSION)) {
  session_start();
}

if (isset($_SESSION["Setor"])) {
	$setor_logado = $_SESSION["Setor"];
}

$start = isset($_GET["start"]) ? (int)$_GET["start"]:0;
$limit = isset($_GET["limit"]) ? (int)$_GET["limit"]:15;
$query = $_GET["query"];

if($conn){

	$select="SELECT * FROM tab_protocolo WHERE Origem='$setor_logado'";
	$sql_select=mysql_query($select) or die (mysql_error());
	$total_registros = mysql_num_rows($sql_select);

	if($total_registros) {
		
		
		if (empty($query)) {
			$query2="SELECT * FROM tab_protocolo WHERE Origem='$setor_logado' ORDER BY IDProtocolo DESC LIMIT $start,$limit";
			$sql_select2=mysql_query($query2) or die (mysql_error());			
		} else {
			$query2="SELECT * FROM tab_protocolo WHERE Origem='$setor_logado' AND
			(Numero LIKE '$query%' OR Origem LIKE '$query%' OR Destino LIKE '$query%' OR End_Destino LIKE '$query%')
			ORDER BY IDProtocolo DESC LIMIT $start,$limit";
			$sql_select2=mysql_query($query2) or die (mysql_error());
			$total_registros = mysql_num_rows($sql_select2);
		}
		
		$arrJson = array();
	
		while($row= mysql_fetch_object($sql_select2)) {
         	$arrJson[] = array(
				'Numero' => $row->Numero,
				'Origem' => $row->Origem,
				'Destino' => $row->Destino,
				'End_Destino' => $row->End_Destino,
				'Descricao_Anexo' => $row->Descricao_Anexo,
				'Data' => $row->Data
	        );
     	}
	}
}

echo json_encode(array("rows" => $arrJson,"total" => $total_registros));

?>